package com.wzxy.pf.loginlog.service.impl;

import com.wzxy.pf.loginlog.entity.Loginlog;
import com.wzxy.pf.loginlog.entity.User;
import com.wzxy.pf.loginlog.mapper.LoginlogMapper;
import com.wzxy.pf.loginlog.service.LoginlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhl
 * @since 2023-04-01
 */
@Service
public class LoginlogServiceImpl extends ServiceImpl<LoginlogMapper, Loginlog> implements LoginlogService {
@Resource
LoginlogMapper loginlogMapper;
    @Transactional
    @Override
    public int savelogin(User user, HttpServletRequest request) {
        String ip;
        if (request.getHeader("x-forwarded-for") == null) {
            ip=  request.getRemoteAddr();
            System.out.println("a"+ip);
        }
        else {
            ip=request.getHeader("x-forwarded-for");
            System.out.println("b"+ip);
        }
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        String createtime=formatter.format(date);
        Loginlog loginlog=new Loginlog();
        if(user!=null){
           loginlog.setAccount(user.getAccount());
           loginlog.setIp(ip);
           loginlog.setType(0);
           loginlog.setCreatTime(createtime);
        }
        return loginlogMapper.insert(loginlog);
    }
    @Transactional
    @Override
    public int savelogout(User user, HttpServletRequest request) {
        String ip;
        if (request.getHeader("x-forwarded-for") == null) {
            ip=  request.getRemoteAddr();
            System.out.println("a"+ip);
        }
        else {
            ip=request.getHeader("x-forwarded-for");
            System.out.println("b"+ip);
        }
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        String createtime=formatter.format(date);
        Loginlog loginlog=new Loginlog();
        if(user!=null){
            loginlog.setAccount(user.getAccount());
            loginlog.setIp(ip);
            loginlog.setType(1);
            loginlog.setCreatTime(createtime);
        }
        return loginlogMapper.insert(loginlog);
    }
}
